package com.ken.callblock2.view;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

import com.ken.callblock2.CallBlock2;
import com.ken.callblock2.R;
import com.ken.callblock2.listener.PhoneCallListener;
import com.ken.callblock2.tools.KENLog;
import com.ken.callblock2.utils.ContactBean;

import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.RawContacts;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ContactsViewFragment extends BaseFragment implements OnItemClickListener {

	private ListView 			contactList;
	private ProgressBar 		progressBar;
	private List<ContactBean> 	contactBeanList = new LinkedList<ContactBean>();
	private ContactAdapter 		contactAdapter;
	//
	public static final int CALL 			= 0;
	public static final int SMS 			= 1;
	public static final int NUMBER_BLOCK 	= 2;
	public static final int SILENT 			= 3;
	public static final int VIBRATE 		= 4;

	boolean isAlive = false;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		isAlive = true;
		View v 	= inflater.inflate(R.layout.frame_contacts_view, container, false);
		return v;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onDestroyView() {
		isAlive = false;
		super.onDestroyView();
	}

	private void init() {
		contactBeanList.addAll(getApp().contactBeanList);
		contactList 	= (ListView) this.getView().findViewById(R.id.lv_contacts_list);
		progressBar 	= (ProgressBar) this.getView().findViewById(R.id.pb_contacts_progressbar);
		contactAdapter 	= new ContactAdapter(getActivity());
		contactList.setAdapter(contactAdapter);
		contactList.setOnItemClickListener(this);
		//
		progressBar.setVisibility(View.VISIBLE);
		new GetContactAsync().execute();
	}

	Handler getContacthandle = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			if (isAlive) {
				contactBeanList.clear();
				contactBeanList.addAll(getApp().contactBeanList);
				contactAdapter.notifyDataSetChanged();
				progressBar.setVisibility(View.INVISIBLE);
			}
		}
	};

	private class GetContactAsync extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			try {
				getApp().getContactToList();
			} catch (NullPointerException e) {
				isAlive = false;
				KENLog.e("ken", e.getMessage() + "ContactsViewFragment is destory");
			}
			getContacthandle.sendEmptyMessage(0);
			return null;
		}

	}

	public String getAllPhoneNumbers(String lookUp_Key) {
		String allPhoneNo = "";

		// Phone info are stored in the ContactsContract.Data table
		Uri phoneUri 	= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		String[] proj2 	= {	ContactsContract.CommonDataKinds.Phone.NUMBER,
							ContactsContract.CommonDataKinds.Phone.PHOTO_ID };
		// using lookUp key to search the phone numbers
		String selection 		= ContactsContract.Data.LOOKUP_KEY + "=?";
		String[] selectionArgs 	= { lookUp_Key };
		Cursor cur = getApp().getContentResolver().query(phoneUri, proj2, selection, selectionArgs, null);
		while (cur.moveToNext()) {
			allPhoneNo += cur.getString(0) + " ";
		}
		
		return allPhoneNo;
	}

	private byte[] queryContactImage(String photo_id) {
		byte[] contactIcon = null;
		if (photo_id == null || photo_id.equals(""))
			return null;
		try {
			String[] projection = new String[] { ContactsContract.Data.DATA15 };
			String selection = "ContactsContract.Data._ID = " + photo_id;
			Cursor cur = getApp().getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, selection, null, null);
			cur.moveToFirst();

			if (cur.getBlob(cur.getColumnIndex(ContactsContract.Data.DATA15)) != null) {
				contactIcon = cur.getBlob(cur.getColumnIndex(ContactsContract.Data.DATA15));
				// bitmap=BitmapFactory.decodeByteArray(contactIcon, 0,
				// contactIcon.length);
			}
			cur.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return contactIcon;
	}

	public byte[] openPhoto(long contactId) {
		Uri contactUri 	= ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
		Uri photoUri 	= Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
		Cursor cursor 	= getApp().getContentResolver().query(photoUri, new String[] { Contacts.Photo.PHOTO }, null, null, null);
		if (cursor == null) {
			return null;
		}
		try {
			if (cursor.moveToFirst()) {
				byte[] data = cursor.getBlob(0);
				if (data 	!= null) {
					return data;
				}
			}
		} finally {
			cursor.close();
		}
		return null;
	}

	public byte[] loadContactPhoto(long id) {
		Uri uri 			= ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
		InputStream input 	= ContactsContract.Contacts.openContactPhotoInputStream(getApp().getContentResolver(), uri);
		if (input == null) {
			return null;
		}
		try {
			ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
			int ch;
			while ((ch = input.read()) != -1) {
				bytestream.write(ch);
			}
			byte imgdata[] = bytestream.toByteArray();
			bytestream.close();
			return imgdata;
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}

	}

	// ======================

	class ContactAdapter extends BaseAdapter {

		Context mContext;
		LayoutInflater mInflater;

		public ContactAdapter(Context context) {
			mContext = context;
			mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return contactBeanList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;

			if (convertView == null || convertView instanceof TextView) {
				convertView = mInflater.inflate(R.layout.contacts_list_item, null);

				holder = new ViewHolder();
				holder.name 			= (TextView) convertView.findViewById(R.id.tv_contacts_item_name);
				holder.phone_number 	= (TextView) convertView.findViewById(R.id.tv_contacts_item_number);
				holder.photo 			= (ImageView) convertView.findViewById(R.id.iv_contacts_item_photo);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			//
			holder.name.setText(contactBeanList.get(position).name);
			holder.phone_number.setText(contactBeanList.get(position).phone_number);
			//
			byte[] img = contactBeanList.get(position).photo;
			if (img != null) {
				holder.photo.setImageBitmap(BitmapFactory.decodeByteArray(img, 0, img.length));
			} else {
				holder.photo.setImageDrawable(null);
			}
			//
			return convertView;
		}

	}

	class ViewHolder {
		TextView 	name;
		TextView 	phone_number;
		ImageView 	photo;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		final ContactBean contactBean = contactBeanList.get(arg2);
		String[] items = getResources().getStringArray( R.array.contact_item_options);

		new AlertDialog.Builder(getActivity()).setItems(items,
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case CALL:
							// 叫出撥號程式
							Uri uri_call = Uri.parse("tel:" + contactBean.phone_number);
							Intent it_call = new Intent(Intent.ACTION_DIAL, uri_call);
							startActivity(it_call);
							break;
						case SMS:
							// 傳送簡訊
							Uri uri_sms = Uri.parse("smsto:" + contactBean.phone_number);
							Intent it_sms = new Intent(Intent.ACTION_SENDTO, uri_sms);
							startActivity(it_sms);
							break;
						case NUMBER_BLOCK:
							getApp().addBlackMap(contactBean.phone_number, String.valueOf(PhoneCallListener.RINGER_MODE_EndCall));
							getApp().blockListNotifyHandler.sendEmptyMessage(0);
							break;
						case SILENT:
							getApp().addBlackMap(contactBean.phone_number, String.valueOf(PhoneCallListener.RINGER_MODE_Silent));
							getApp().blockListNotifyHandler.sendEmptyMessage(0);
							break;
						case VIBRATE:
							getApp().addBlackMap(contactBean.phone_number, String.valueOf(PhoneCallListener.RINGER_MODE_Vibrate));
							getApp().blockListNotifyHandler.sendEmptyMessage(0);
							break;
						}
					}
				}).show();
	}

}
